package com.wh.emall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wh.emall.common.utils.PageUtils;
import com.wh.emall.common.utils.Query;
import com.wh.emall.product.dao.CategoryDao;
import com.wh.emall.product.entity.CategoryEntity;
import com.wh.emall.product.service.CategoryBrandRelationService;
import com.wh.emall.product.service.CategoryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1. 查出所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //2. 组装成父子的树形结构
        List<CategoryEntity> level1Menues = categoryEntities.stream().filter(entity -> entity.getParentCid() == 0)
                .map((menu) -> {
                    menu.setChildren(getChildrens(menu, categoryEntities));
                    return menu;
                })
                .sorted((m1, m2) -> {
                    return (m1.getSort() == null ? 0 : m1.getSort())
                            - (m2.getSort() == null ? 0 : m2.getSort());
                })
                .collect(Collectors.toList());
        return level1Menues;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCategoryPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);

        Collections.reverse(parentPath);
        return (Long[]) parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新
     *
     * @param category
     */
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);

//        CategoryBrandRelationEntity entity = new CategoryBrandRelationEntity();
//        entity.setCatelogName(category.getName());
//        entity.setCatelogId(category.getCatId());
//        QueryWrapper<CategoryBrandRelationEntity> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("catelog_id",entity.getCatelogId());
//
//        categoryBrandRelationService.update(entity,queryWrapper);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    // 递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity entity, List<CategoryEntity> all) {
        List<CategoryEntity> collect = all.stream().filter(e -> {
            return e.getParentCid() == entity.getCatId();
        }).map(e2 -> {
            //找子菜单
            e2.setChildren(getChildrens(e2, all));
            return e2;
        }).sorted((m1, m2) -> {
            // 菜单排序
            return (m1.getSort() == null ? 0 : m1.getSort())
                    - (m2.getSort() == null ? 0 : m2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }
}